package main.controller;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import main.*;
import main.cipher.TokenUtils;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;

@Controller
public class MailRegisterPageController {
    /**
     * 用户注册时，邮箱确认后发送邮件，然后浏览器中显示的页面
     * @param mail
     * @param modelMap
     * @return
     */
    @RequestMapping (value = "/mailregisterresponse")
    public String mailRegisterResponse(@RequestParam String mail, ModelMap modelMap) {
        String now = new Timestamp(new Date().getTime()).toString();
        JSONObject jo = new JSONObject();
        jo.put("mail", mail);
        jo.put("time", now);
        jo.put("random", StringHelper.getAlphaNumericString(16));
        String param = jo.toString();
        param = TokenUtils.encrypt(param);

        String content = makeContent(param);
        String title = GlobalConfig.siteName + "注册确认邮件";

        MailHelper.sendMail(GlobalConfig.siteName, GlobalConfig.mailSender, GlobalConfig.mailSenderPwd, mail, title, content);

        modelMap.put("mail", mail);
        modelMap.put("siteName", GlobalConfig.siteName);
        return "mailRegisterResponsePage";
    }

    /**
     * 用户点击注册邮箱中的链接，用来激活后会走向的页面
     * @param i
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/mailverify")
    public String mailRegisterVerify(@RequestParam String i, ModelMap modelMap) {
        String origin = TokenUtils.decrypt(i);
        JSONObject jo = new JSONObject(origin);
        String mail = jo.get("mail").toString();
        String time = jo.get("time").toString();

        Timestamp timestamp = Timestamp.valueOf(time);
        boolean before = TimeHelper.isTimeNHoursBefore(timestamp, 2);

        String resultUrl = "/firstTimePasswordSet";
        modelMap.put("siteName", GlobalConfig.siteName);
        if (before) {
            modelMap.put("reason", "激活链接已经过时，请重新使用注册");
            modelMap.put("error", true);
            resultUrl = "/mailRegisterVerifyPage";
        }
        else {
            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUser);
            long count = collection.countDocuments(Filters.eq("email", mail));
            if (count > 0) {
                modelMap.put("error", true);
                modelMap.put("reason", "邮箱已经存在。可能的问题：邮箱已经被绑定。");
                resultUrl = "/mailRegisterVerifyPage";
            }
            else {
                modelMap.put("currentAccount", mail);
            }
        }

        return resultUrl;
    }

    /**
     * 邮箱绑定时用户点击邮件内的绑定链接会到此方法
     * @param l
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/mailbind")
    public String mailBind(@RequestParam String l,HttpServletRequest request, ModelMap modelMap) {
        String origin = TokenUtils.decrypt(l);
        JSONObject jo = new JSONObject(origin);
        String mail = jo.get("mail").toString();
        String time = jo.get("time").toString();
        String uuid = jo.get("uuid").toString();

        Timestamp timestamp = Timestamp.valueOf(time);
        boolean before = TimeHelper.isTimeNHoursBefore(timestamp, 2);

        String resultUrl = "/mailBindResult";
        modelMap.put("siteName", GlobalConfig.siteName);
        if (before) {
            modelMap.put("error", true);
            modelMap.put("reason", "链接已经失效（超过2小时）");
        }
        else if (!AccountHelper.isExistFromUUID(uuid)) {
            modelMap.put("error", true);
            modelMap.put("reason", "用户无效");
        }
        else {
            AccountHelper.updateEmailFromUUID(uuid, mail);
            modelMap.put("error", false);
        }
        return resultUrl;
    }

    /**
     *
     * @param p
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/findp")
    public String mailFindPassword(@RequestParam String p, ModelMap modelMap) {
        String origin = TokenUtils.decrypt(p);
        JSONObject jo = new JSONObject(origin);
        String mail = jo.get("mail").toString();
        String time = jo.get("time").toString();

        Timestamp timestamp = Timestamp.valueOf(time);
        boolean before = TimeHelper.isTimeNHoursBefore(timestamp, 2);
        String resultUrl = "/resetPasswordPage";
        modelMap.put("siteName", GlobalConfig.siteName);
        if (before) {
            modelMap.put("error", true);
            modelMap.put("reason", "您点击的链接已经过期");
        }
        else {
            if (AccountHelper.isExistFromEmail(mail)) {
                modelMap.put("error", false);
                modelMap.put("email", mail);
            }
            else {
                modelMap.put("error", true);
                modelMap.put("reason", "邮箱地址在网站内不存在");
            }
        }

        return resultUrl;
    }

    /**
     * 制作用户注册确认的邮箱内容（发送给用户邮箱的确认链接）
     * @param param
     * @return
     */
    private String makeContent(String param) {
        String url = null;

        try {
            url = GlobalConfig.siteUrl + GlobalConfig.verifyEmailPrefix + URLEncoder.encode(param, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            Logman.error(e.getStackTrace().toString());
        }

        StringBuilder stringBuilder = new StringBuilder("尊敬的");
        stringBuilder.append(GlobalConfig.siteName);
        stringBuilder.append("用户：");
        stringBuilder.append("\n");
        stringBuilder.append("\t感谢您在网站的注册，您只需要点击下面的连接即可完成账号激活。激活链接（2小时有效，前后无空格）：");
        stringBuilder.append("\n");
        stringBuilder.append("                ");
        stringBuilder.append(url);
        stringBuilder.append("                ");
        stringBuilder.append("\n");
        stringBuilder.append("\n");
        stringBuilder.append("如果激活链接无法点击，请复制到浏览器地址栏，再直接访问。如果绑定非您发起，请忽略。");

        return stringBuilder.toString();
    }
}
